package red.yancloud.www.ui.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.dyhdyh.widget.loading.dialog.LoadingDialog
import com.example.zhouwei.library.CustomPopWindow
import com.gyf.immersionbar.ImmersionBar
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.xiao.nicevideoplayer.Clarity
import com.xiao.nicevideoplayer.NiceVideoPlayer
import com.xiao.nicevideoplayer.NiceVideoPlayerManager
import com.xiao.nicevideoplayer.TxVideoPlayerController
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.ig.DefaultImageGetter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_video_info.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import org.jsoup.Jsoup
import red.yancloud.www.R
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.FavoriteState
import red.yancloud.www.internet.bean.VideoInfo
import red.yancloud.www.ui.dialog.LoadingCallback
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.ToastUtils
import java.util.*

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/12 14:47
 * E_Mail：yh131412hys@163.com
 * Describe：视频页面
 * Change：
 * @Version：V1.0
 */
class VideoInfoActivity : AppCompatActivity(), View.OnClickListener {

    private val TAG = "VideoInfoActivity"

    private var videoId: String =""
    private var title: String =""
    private var videoUrl: String =""

    private var id:String = ""
    private var state: Int = -1
    private var currentState: Int = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_info)

        val loadingDialog = LoadingDialog.make(this, LoadingCallback()).create()
        loadingDialog.setCancelable(true)
        loadingDialog.setCanceledOnTouchOutside(true)
        loadingDialog.show()

        videoId = intent.getStringExtra("id")
        RedCloudApis.getInstance().getVideo(videoId, object : Observer<VideoInfo> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: VideoInfo) {

                    if (t.code == Constants.SYSTEM_OK&&t.data!=null&&t.data.video!=null) {

                        title = t.data.video.title
                        videoActivity_title_tv.text = title
                        videoActivity_website_tv.text = t.data.video.tag
                        videoActivity_time_tv.text = t.data.video.addtime
                        RichText.from(t.data.video.content).imageGetter(DefaultImageGetter()).into(videoActivity_content_tv)

                        if (!TextUtils.isEmpty(t.data.video.content)) {

                            val videoSource = Jsoup.parse(t.data.video.content).select("video").select("source").attr("src")
                            Log.d(TAG, videoSource)
                            videoActivity_niceVideoPlayer.setPlayerType(NiceVideoPlayer.TYPE_IJK) // IjkPlayer or MediaPlayer
                            videoUrl = /*Constants.BASE_RED_CLOUD_HOST_URL*/"http://www.yancloud.red" + videoSource

                            Log.d(TAG,"content====$videoSource")


                            videoActivity_niceVideoPlayer.setUp(videoUrl,null)
                            val controller = TxVideoPlayerController(this@VideoInfoActivity)
                            controller.setTitle(title)
//                        controller.setTitle("Beautiful China...")
//                        controller.setLenght(117000)
//                        controller.setClarity(clarites, 0)
                            Glide.with(applicationContext)
                                .load(Constants.BASE_RED_CLOUD_HOST_URL.plus(t.data.video.thumbnail)/*"http://imgsrc.baidu.com/image/c0%3Dshijue%2C0%2C0%2C245%2C40/sign=304dee3ab299a9012f38537575fc600e/91529822720e0cf3f8b77cd50046f21fbe09aa5f.jpg"*/)
                                .placeholder(R.drawable.img_default)
                                .into(controller.imageView())
                            videoActivity_niceVideoPlayer.setController(controller)
                        }

                        val fileAddress = t.data.video.fileaddress
                        if (!TextUtils.isEmpty(fileAddress)) {

                            if (fileAddress.startsWith("http")) {

                                AppUtils.openBrowser(this@VideoInfoActivity, fileAddress)
                                finish()
                            }else{
                                Log.d(TAG,"content====${Constants.BASE_RED_CLOUD_HOST_URL + fileAddress}")

//                                AppUtils.openBrowser(this@VideoInfoActivity, Constants.BASE_RED_CLOUD_HOST_URL+fileAddress)

                                videoActivity_niceVideoPlayer.setPlayerType(NiceVideoPlayer.TYPE_IJK) // IjkPlayer or MediaPlayer
                                videoUrl = /*Constants.BASE_RED_CLOUD_HOST_URL*/"http://www.yancloud.red" + fileAddress

                                videoActivity_niceVideoPlayer.setUp(videoUrl,null)
                                val controller = TxVideoPlayerController(this@VideoInfoActivity)
                                controller.setTitle(title)
//                        controller.setTitle("Beautiful China...")
//                        controller.setLenght(117000)
//                        controller.setClarity(clarites, 0)
                                Glide.with(applicationContext)
                                    .load(Constants.BASE_RED_CLOUD_HOST_URL.plus(t.data.video.thumbnail)/*"http://imgsrc.baidu.com/image/c0%3Dshijue%2C0%2C0%2C245%2C40/sign=304dee3ab299a9012f38537575fc600e/91529822720e0cf3f8b77cd50046f21fbe09aa5f.jpg"*/)
                                    .placeholder(R.drawable.img_default)
                                    .into(controller.imageView())
                                videoActivity_niceVideoPlayer.setController(controller)
                            }
                        }
                    }

                    loadingDialog.dismiss()
                }

                override fun onError(e: Throwable) {

                    Log.d(TAG,e.toString())
                    loadingDialog.dismiss()
                }
            })

        initView()
    }

    private fun initView() {

        ImmersionBar.with(this).statusBarView(R.id.top_view)
            .navigationBarColor(R.color.colorPrimary)
            .fullScreen(true)
            .addTag("PicAndColor")
            .init()

        back_iv.setOnClickListener(this)
        share_tv.setOnClickListener(this)
    }

    private val clarites: List<Clarity>
        get() {
            val clarities = ArrayList<Clarity>()
            clarities.add(
                Clarity(
                    "标清",
                    "270P",
                    "http://play.g3proxy.lecloud.com/vod/v2/MjUxLzE2LzgvbGV0di11dHMvMTQvdmVyXzAwXzIyLTExMDc2NDEzODctYXZjLTE5OTgxOS1hYWMtNDgwMDAtNTI2MTEwLTE3MDg3NjEzLWY1OGY2YzM1NjkwZTA2ZGFmYjg2MTVlYzc5MjEyZjU4LTE0OTg1NTc2ODY4MjMubXA0?b=259&mmsid=65565355&tm=1499247143&key=f0eadb4f30c404d49ff8ebad673d3742&platid=3&splatid=345&playid=0&tss=no&vtype=21&cvid=2026135183914&payff=0&pip=08cc52f8b09acd3eff8bf31688ddeced&format=0&sign=mb&dname=mobile&expect=1&tag=mobile&xformat=super"
                )
            )
            clarities.add(
                Clarity(
                    "高清",
                    "480P",
                    "http://play.g3proxy.lecloud.com/vod/v2/MjQ5LzM3LzIwL2xldHYtdXRzLzE0L3Zlcl8wMF8yMi0xMTA3NjQxMzkwLWF2Yy00MTk4MTAtYWFjLTQ4MDAwLTUyNjExMC0zMTU1NTY1Mi00ZmJjYzFkNzA1NWMyNDc4MDc5OTYxODg1N2RjNzEwMi0xNDk4NTU3OTYxNzQ4Lm1wNA==?b=479&mmsid=65565355&tm=1499247143&key=98c7e781f1145aba07cb0d6ec06f6c12&platid=3&splatid=345&playid=0&tss=no&vtype=13&cvid=2026135183914&payff=0&pip=08cc52f8b09acd3eff8bf31688ddeced&format=0&sign=mb&dname=mobile&expect=1&tag=mobile&xformat=super"
                )
            )
            clarities.add(
                Clarity(
                    "超清",
                    "720P",
                    "http://play.g3proxy.lecloud.com/vod/v2/MjQ5LzM3LzIwL2xldHYtdXRzLzE0L3Zlcl8wMF8yMi0xMTA3NjQxMzkwLWF2Yy00MTk4MTAtYWFjLTQ4MDAwLTUyNjExMC0zMTU1NTY1Mi00ZmJjYzFkNzA1NWMyNDc4MDc5OTYxODg1N2RjNzEwMi0xNDk4NTU3OTYxNzQ4Lm1wNA==?b=479&mmsid=65565355&tm=1499247143&key=98c7e781f1145aba07cb0d6ec06f6c12&platid=3&splatid=345&playid=0&tss=no&vtype=13&cvid=2026135183914&payff=0&pip=08cc52f8b09acd3eff8bf31688ddeced&format=0&sign=mb&dname=mobile&expect=1&tag=mobile&xformat=super"
                )
            )
            clarities.add(
                Clarity(
                    "蓝光",
                    "1080P",
                    "http://play.g3proxy.lecloud.com/vod/v2/MjQ5LzM3LzIwL2xldHYtdXRzLzE0L3Zlcl8wMF8yMi0xMTA3NjQxMzkwLWF2Yy00MTk4MTAtYWFjLTQ4MDAwLTUyNjExMC0zMTU1NTY1Mi00ZmJjYzFkNzA1NWMyNDc4MDc5OTYxODg1N2RjNzEwMi0xNDk4NTU3OTYxNzQ4Lm1wNA==?b=479&mmsid=65565355&tm=1499247143&key=98c7e781f1145aba07cb0d6ec06f6c12&platid=3&splatid=345&playid=0&tss=no&vtype=13&cvid=2026135183914&payff=0&pip=08cc52f8b09acd3eff8bf31688ddeced&format=0&sign=mb&dname=mobile&expect=1&tag=mobile&xformat=super"
                )
            )
            return clarities
        }

    override fun onStop() {
        super.onStop()
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer()
    }

    override fun onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) {
            return
        }
        super.onBackPressed()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv-> finish()
            R.id.share_tv -> {

                if (!NetworkUtils.isConnected(this)) {
                    ToastUtils.toastNetErrorMsg()
                    return
                }

                if (UserInfoShardPreference.instance.isLogin) {

                    RedCloudApis.getInstance().getFavoriteState(UserInfoShardPreference.instance.uid,videoId,Constants.CollectModel.MEDIA,object : Observer<FavoriteState> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: FavoriteState) {

                            if (t.code == Constants.SYSTEM_OK) {

                                if (t.data != null) {

                                    id = t.data.id
                                    state = Constants.CollectType.COLLECT
                                }else{

                                    state = Constants.CollectType.NOT_COLLECT
                                }

                                currentState = state

                                initPopupWindow(v)
                            }
                        }

                        override fun onError(e: Throwable) {

                            state = Constants.CollectType.NOT_COLLECT
                            currentState = state
                            initPopupWindow(v)
                        }
                    })
                }else{

                    state = Constants.CollectType.NOT_COLLECT
                    currentState = state
                    initPopupWindow(v)
                }
            }
        }
    }

    private fun initPopupWindow(v: View?) {

        val contentView =
            LayoutInflater.from(this@VideoInfoActivity).inflate(R.layout.news_info_popup_window_layout, null)
        //创建并显示popWindow -360
        val mCustomPopWindow = CustomPopWindow.PopupWindowBuilder(this@VideoInfoActivity)
            .setView(contentView)
            .create()
            .showAsDropDown(v, -20, 10)

        contentView.findViewById<AppCompatTextView>(R.id.share_tv).setOnClickListener {

            val image = UMImage(this, R.mipmap.ic_launcher)
            val web = UMWeb(/*videoUrl*/"http://www.yancloud.red/Portal/Media/info/?id=$videoId") //切记切记 这里分享的链接必须是http开头
            web.title = title//标题
            web.setThumb(image)  //缩略图
            web.description = "你要分享内容的描述"//描述

            ShareAction(this).withMedia(image).withMedia(web)
                .setDisplayList(
                    SHARE_MEDIA.SINA,
                    SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,
                    SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                    SHARE_MEDIA.MORE)
                .setCallback(umShareListener).open()
            mCustomPopWindow.dissmiss()
        }

        val collectTv = contentView.findViewById<AppCompatTextView>(R.id.collect_tv)
        if (state == Constants.CollectType.COLLECT) {

            val drawable = resources.getDrawable(R.mipmap.news_collect_ic)
            // 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            collectTv.setCompoundDrawables(drawable, null, null, null)
        }

        collectTv.setOnClickListener {

            if (UserInfoShardPreference.instance.isLogin) {

                if (state == Constants.CollectType.COLLECT) {

                    RedCloudApis.getInstance().myCollectDelete(UserInfoShardPreference.instance.uid,id,object : Observer<ResponseBody> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: ResponseBody) {

                            val result = String(t.bytes())

                            if (!TextUtils.isEmpty(result)) {

                                val jsonObject = JSONObject.parseObject(result)

                                if (jsonObject.getString("code") == Constants.SYSTEM_OK) {

                                    val drawable = resources.getDrawable(R.mipmap.news_not_collect_ic)
                                    // 这一步必须要做,否则不会显示.
                                    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                                    collectTv.setCompoundDrawables(drawable, null, null, null)

                                    ToastUtils.showToast(getString(R.string.cancel_collect))
                                    mCustomPopWindow.dissmiss()

                                    state = Constants.CollectType.NOT_COLLECT
                                }else{

                                    ToastUtils.showToast(jsonObject.getString("msg"))
                                }
                            }else{

                                ToastUtils.showToast(getString(R.string.cancel_collect_failure))
                            }
                        }

                        override fun onError(e: Throwable) {
                        }
                    })

                }else if(state == Constants.CollectType.NOT_COLLECT){

                    RedCloudApis.getInstance().addFavorite(UserInfoShardPreference.instance.uid,title,videoId,Constants.CollectModel.MEDIA,object : Observer<ResponseBody> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: ResponseBody) {

                            val result = String(t.bytes())
                            if (!TextUtils.isEmpty(result)) {

                                val parseObject = JSONObject.parseObject(result)
                                if (parseObject.getString("code") == Constants.SYSTEM_OK) {

                                    val drawable = resources.getDrawable(R.mipmap.news_collect_ic)
                                    // 这一步必须要做,否则不会显示.
                                    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                                    collectTv.setCompoundDrawables(drawable, null, null, null)

                                    ToastUtils.showToast(getString(R.string.collect_success))
                                    state = Constants.CollectType.COLLECT
                                }else{

                                    ToastUtils.showToast(getString(R.string.collect_failure))
                                }

                                mCustomPopWindow.dissmiss()
                            }
                        }

                        override fun onError(e: Throwable) {

                            ToastUtils.showToast(getString(R.string.collect_failure))
                            mCustomPopWindow.dissmiss()
                        }
                    })
                }
                //                    collectTv.setText(R.string.already_collect)
            }else{

                ToastUtils.showToast(R.string.not_login_prompt)
                startActivity(Intent(this,LoginActivity::class.java))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        if (currentState != state) {

            EventBus.getDefault().post(MessageEvent(Constants.REFRESH_MY_COLLECT,""))
        }
    }

    private val umShareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {

            ToastUtils.showToast("分享成功了")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {

            ToastUtils.showToast("分享失败" + t.message)
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {

        }
    }
}
